//
//  MobileRegistFirstStepView.m
//  QRMaster
//
//  Created by myApple on 16/3/2.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "MobileRegistFirstStepView.h"
#import "LineView.h"
#import "validateInputValue.h"
#import "MZSelectableLabel.h"

@interface MobileRegistFirstStepView ()<UITextFieldDelegate>
{
    UITextField * areaTextField;//国家或者地区
    UITextField * UserNameTextField;//账号
    UITextField * PassWordTextField;//密码
    UIButton * ResgistBtn;
    UIButton * emailResgistBtn;
    UIButton * seePWDBtn;//查看密码的眼睛
    
    LineView * areaLine;
    LineView * userNameLine;
    LineView * passWordLine;
    
    MZSelectableLabel * promtLabel;
    
    BOOL areaCodeFlag;//区号是否正确
    BOOL mobileFlag;//是否输入电话
    BOOL passWordFlag;//是否输入密码
}

@end

@implementation MobileRegistFirstStepView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        areaCodeFlag = YES;
        mobileFlag = NO;
        passWordFlag = NO;
        [self prepareView];
    }
    return self;
}

-(void)prepareView
{
    float ScreenWidth = self.frame.size.width;
    float ScreenHeight = self.frame.size.height;
    float x = 22;
    float y = 40;
    float width = ScreenWidth - 2 * x - 100;
    float height = 39;
    //国家或者地区
    areaTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    areaTextField.secureTextEntry = YES;
    areaTextField.userInteractionEnabled = NO;
    areaTextField.delegate = self;
    areaTextField.font = [UIFont systemFontOfSize:13.0];
    areaTextField.borderStyle = UITextBorderStyleNone;
    areaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:areaTextField];
    areaLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    areaLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:areaLine];
    
    UILabel * HeaderLabel = [[UILabel alloc]initWithFrame:CGRectMake(4, 30, 100, 20)];
    HeaderLabel.text = NSLocalizedString(@"areaOrCountry", nil);
    HeaderLabel.font = [UIFont systemFontOfSize:14.0];
    areaTextField.leftView = HeaderLabel;
    areaTextField.leftViewMode = UITextFieldViewModeAlways;
    
    _areaTextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _areaTextBtn.frame = CGRectMake(self.frame.size.width - 122, 42, 100, 39);
    [_areaTextBtn setTitle:NSLocalizedString(@"China", nil) forState:0];
    [_areaTextBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    _areaTextBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [_areaTextBtn addTarget:self action:@selector(changeArea) forControlEvents:UIControlEventTouchUpInside];
    _areaTextBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self addSubview:_areaTextBtn];
    
    //手机注册
    y += height + 5;
    x = 30;
    width = 60;
    height = 39;
    
    _areaCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    _areaCodeTextField.font = [UIFont systemFontOfSize:13.0];
    _areaCodeTextField.text = @"86";
    _areaCodeTextField.borderStyle = UITextBorderStyleNone;
    _areaCodeTextField.delegate = self;
    _areaCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self addSubview:_areaCodeTextField];
    
    UILabel * addLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, areaLine.frame.size.height + areaLine.frame.origin.y + 13, 10, 18)];
    addLabel.text = @"+";
    addLabel.textAlignment = NSTextAlignmentRight;
    addLabel.font = [UIFont systemFontOfSize:13.0];
    [self addSubview:addLabel];
    
    x = 95;
    width = ScreenWidth - x - 16;
    UserNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    UserNameTextField.placeholder = NSLocalizedString(@"loginPromt", nil);
    UserNameTextField.font = [UIFont systemFontOfSize:14.0];
    UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    UserNameTextField.keyboardType = UIKeyboardTypeNumberPad;
    UserNameTextField.delegate = self;
    [self addSubview:UserNameTextField];
    userNameLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:userNameLine];
    
    //密码
    y += height + 5;
    width = ScreenWidth - x - 16;
    PassWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    PassWordTextField.secureTextEntry = YES;
    PassWordTextField.placeholder = NSLocalizedString(@"passPromt", nil);
    PassWordTextField.delegate = self;
    PassWordTextField.font = [UIFont systemFontOfSize:14.0];
    PassWordTextField.borderStyle = UITextBorderStyleNone;
    PassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:PassWordTextField];
    passWordLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:passWordLine];
    
//    UIImageView * passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(22, y + 10, 20, 20)];
//    UIImage * passWordImg = [UIImage imageNamed:@"loginPWDImage"];
//    passWordView.image = passWordImg;
//    [self addSubview:passWordView];
    UILabel * passWordLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, y+10, 60, 20)];
    passWordLabel.text = NSLocalizedString(@"passWord", nil);
    passWordLabel.font = [UIFont systemFontOfSize:13.0];
    passWordLabel.textColor= UIColorFromRGB(0x333333);
    [self addSubview:passWordLabel];
    
    //小眼睛
    UIImageView * oldSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    PassWordTextField.rightViewMode = UITextFieldViewModeAlways;
    PassWordTextField.rightView = oldSeeImgView;
    oldSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * oldSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seePwd)];
    [oldSeeImgView addGestureRecognizer:oldSeeTap];
    seePWDBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    seePWDBtn.frame = CGRectMake(14, 14, 16, 12);
    seePWDBtn.selected = NO;
    seePWDBtn.userInteractionEnabled = NO;
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [oldSeeImgView addSubview:seePWDBtn];
    
    //注册
    x = 16;
    y += height + 26;
    width = ScreenWidth - x - 20;
    height = 48;
    ResgistBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [ResgistBtn setTitle:NSLocalizedString(@"registBtn", nil) forState:0];
    [ResgistBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc123,0.5)];
    ResgistBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    ResgistBtn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    [ResgistBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    ResgistBtn.layer.cornerRadius = 5;
    ResgistBtn.layer.masksToBounds = YES;
    ResgistBtn.enabled = NO;
    [ResgistBtn addTarget:self action:@selector(resigstClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:ResgistBtn];
    
    
    //协议
    x = 20;
    y += height + 20;
    width = ScreenWidth - 2 * x;
    height = 30;
    promtLabel = [[MZSelectableLabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"agreement", nil);
    promtLabel.numberOfLines = 0;
    promtLabel.textAlignment = NSTextAlignmentLeft;
    promtLabel.font = [UIFont systemFontOfSize:12.0];
    [self addSubview:promtLabel];
    
    __weak MobileRegistFirstStepView * weakSelf = self;
    promtLabel.selectionHandler = ^(NSRange range,NSString * string)
    {
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(pushAgreement)]) {
            [weakSelf.delegate pushAgreement];
        }
    };
    
    NSMutableAttributedString * astr = [[NSMutableAttributedString alloc]initWithString:promtLabel.text];
    [astr addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:11.0],NSFontAttributeName,UIColorFromRGB(0x7dc234),NSForegroundColorAttributeName, nil] range:[promtLabel.text rangeOfString:NSLocalizedString(@"registAgreement", nil)]];
    promtLabel.attributedText = astr;
    [promtLabel setSelectableRange:[[promtLabel.attributedText string]rangeOfString:NSLocalizedString(@"registAgreement", nil)]];
    
    
    
    //邮箱注册
    x = 0;
    y = ScreenHeight - 60;
    height = 20;
    width = ScreenWidth;
    emailResgistBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    emailResgistBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    emailResgistBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [emailResgistBtn setTitle:NSLocalizedString(@"registByEmail", nil) forState:0];
    [emailResgistBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [emailResgistBtn addTarget:self action:@selector(emailResgist) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:emailResgistBtn];
}


#pragma mark --------textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        userNameLine.backgroundColor = UIColorFromRGB(0x7dc234);
    }
    else if (textField == PassWordTextField) {
        passWordLine.backgroundColor = UIColorFromRGB(0x7dc234);
    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == PassWordTextField) {
        passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
        PassWordTextField.text = textField.text;
    }
    else if(textField == UserNameTextField)
    {
        userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
        UserNameTextField.text = textField.text;
    }
    else if (textField == _areaCodeTextField)
    {
        userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
        _areaCodeTextField.text = textField.text;
    }
    
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (_areaCodeTextField == textField)  //判断是否时我们想要限定的那个输入框
    {
        
        if (range.location >= 4)
        {
            return NO;
        }
        {
            NSString * checkString = _areaCodeTextField.text;
            
            if (![string isEqualToString:@""]) {
                checkString = [checkString stringByAppendingString:string];
            }else{
                //删除的情况
                checkString=[checkString substringToIndex:(checkString.length - 1)];
            }
            
            int i = 0;
            for (i = 0 ; i < AreaCodeArray.count; i ++) {
                if ([checkString isEqualToString:AreaCodeArray[i]]) {
                    [_areaTextBtn setTitle:AreaArray[i] forState:0];
                    areaCodeFlag = YES;
                    break;
                }
            }
            if (i >= AreaCodeArray.count) {
                [_areaTextBtn setTitle:NSLocalizedString(@"errorAreaOrCountry", nil) forState:0];
                areaCodeFlag = NO;
            }
        }
        
    }
    else if(textField == UserNameTextField)
    {
        if (newString.length > 0) {
            mobileFlag = YES;
        }
        else
        {
            mobileFlag = NO;
        }
    }
    else if (textField == PassWordTextField)
    {
        if (newString.length > 0) {
            passWordFlag = YES;
        }
        else
        {
            passWordFlag = NO;
        }

    }
    [self canTapOfRegist];
    return YES;
    
}

-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        mobileFlag = NO;
    }
    else if(textField == PassWordTextField)
    {
        passWordFlag = NO;
    }
    return YES;
}

#pragma mark -------- 切换国家
-(void)changeArea
{
    userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
    if (_delegate && [_delegate respondsToSelector:@selector(choiceArea)]) {
        [_delegate choiceArea];
    }
}


#pragma mark --------- 查看密码
-(void)seePwd
{
    seePWDBtn.selected = !seePWDBtn.selected;
    if (seePWDBtn.selected) {
        PassWordTextField.secureTextEntry = NO;
    }
    else
    {
        PassWordTextField.secureTextEntry = YES;
    }
}


-(void)resigstClick
{
    [self endEditing:YES];
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
    [areaTextField resignFirstResponder];
    int i = 0;
    for (i = 0 ; i < AreaCodeArray.count; i ++) {
        if ([_areaCodeTextField.text isEqualToString:AreaCodeArray[i]]) {
            break;
        }
    }
    if (i >= AreaCodeArray.count) {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAreaOrCountry", nil) superView:self];
        return;
    }
    
//    if (!areaCodeFlag) {
//          [PromptInfoView showMessage:NSLocalizedString(@"errorAreaOrCountry", nil) superView:self];
//        return;
//    }
    UserNameTextField.text = [UserNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (![validateInputValue validateStringIsNull:UserNameTextField.text]) {
        if (![validateInputValue isPureNumandCharacters:UserNameTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil)];
        return;
    }
    if (![validateInputValue validatePassword:PassWordTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"loginingPromt", nil)];
        return;
    }
    
    NSString * locaString = NSLocalizedString(@"registPromt", nil);
    NSString *titleInfo =NSLocalizedString(@"makeSureTelePhone", nil);
    
    NSString * messageString = [NSString stringWithFormat:@"%@%@",locaString,UserNameTextField.text];
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:titleInfo message:messageString delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) otherButtonTitles:NSLocalizedString(@"alterSure", nil), nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [PassWordTextField resignFirstResponder];
    [UserNameTextField resignFirstResponder];
    if (buttonIndex == 1) {
        NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
        [postDict setValue:UserNameTextField.text forKey:@"mobile"];
        [postDict setValue:PassWordTextField.text forKey:@"password"];
        [postDict setValue:_areaCodeTextField.text forKey:@"areaCode"];
        
        if (_delegate && [_delegate respondsToSelector:@selector(Resgsit:)]) {
            [_delegate Resgsit:postDict];
        }
        
    }
}


#pragma mark ---------emailResgister
-(void)emailResgist
{
    if (_delegate && [_delegate respondsToSelector:@selector(resgsitByEmail)]) {
        [_delegate resgsitByEmail];
    }
}


#pragma mark ----------- 判断注册按钮是否能够点击
-(void)canTapOfRegist
{
    if (mobileFlag && areaCodeFlag && passWordFlag) {
        [self registBtnEnable];
    }
    else
    {
        [self registBtnDisenable];
    }
}


#pragma mark ----------注册按钮点击和不可以点击的两种状态
-(void)registBtnEnable
{
    [ResgistBtn setBackgroundColor:UIColorFromRGB(0x7cd234)];
    [ResgistBtn setTitleColor:UIColorFromRGB(0xffffff) forState:0];
    ResgistBtn.enabled = YES;
}

-(void)registBtnDisenable
{
    [ResgistBtn setBackgroundColor:UIColorFromRGBAndA(0x7cd234, 0.5)];
    [ResgistBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    ResgistBtn.enabled = NO;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
